// 上传文件

const fs = require('fs');
const path = require('path');
const { uploadFileError } = require("../main/err.type")
const { APP_BASE_URL, APP_PORT } = require("../utils/dot");

const UploadFileService = require("../srevice/uploadFileService");

const uploadFileService = new UploadFileService();

class uploadFileController {
    async uploadFile(ctx) {
        const file = ctx.request.files.file;
        const name = file.newFilename + file.originalFilename.slice(file.originalFilename.lastIndexOf('.'));
        let filePath = path.join(__dirname, '../public/upload/') + `/${name}`;
        const upStream = fs.createWriteStream(filePath);
        // 上传后将文件信息保存到数据库
        const fileURL = `${APP_BASE_URL}${APP_PORT}/upload/${name}`;
        try {
            await uploadFileService.uploadFile({ fileURL });
            ctx
                .body = {
                code: 200,
                msg: "上传成功",
                data: {
                    url: `${APP_BASE_URL}${APP_PORT}/upload/${name}`
                }
            }
        } catch (error) {
            console.log(error);
            ctx.body = uploadFileError;
            return ctx.app.emit("error", uploadFileError, ctx);
        }


    }
    async findFileById(ctx) {
        const { id } = ctx.query;
        try {
            const res = await uploadFileService.getFileById({ id });
            console.log(res);
            ctx.body = {
                code: 200,
                msg: "查询成功",
                data: res
            }
        } catch (error) {
            console.log(error);
            ctx.body = uploadFileError;
            return ctx.app.emit("error", uploadFileError, ctx);
        }
    }
}
module.exports = new uploadFileController();